package com.servlet;

import com.commons.Constants;
import com.exception.UserNotFoundException;
import com.pojo.Users;
import com.service.UserLoginService;
import com.service.impl.UserLoginServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

/*
* 处理用户登录请求
* */
@WebServlet("/login.do")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String userpwd = req.getParameter("userpwd");
        String code = req.getParameter("code");
        try {
            HttpSession session=req.getSession();
            String codeTemp = (String) session.getAttribute(Constants.Validate_Code);
            if (Objects.equals(code, codeTemp)){
                UserLoginService userLoginService=new UserLoginServiceImpl();
                Users users = userLoginService.userLogin(username, userpwd);
                //建立客户端与服务端的会话状态
                session.setAttribute(Constants.USER_SESSION_KEY,users);
                //获取session对应的key与value
                ServletContext  servletContext=this.getServletContext();
                HttpSession temp=(HttpSession) servletContext.getAttribute(users.getUserid()+"");
                if (temp!=null){
                    servletContext.removeAttribute(users.getUserid()+"");
                    temp.invalidate();
                }
                servletContext.setAttribute(users.getUserid()+"",session);
                //使用重定向方式跳转到首页,当用户登录成功后到的页面应该是个人首页
                resp.sendRedirect("main.jsp");
            }else {
                req.setAttribute(Constants.REQUEST_MSG,"验证码有误,请重新输入");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }
        }catch (UserNotFoundException e){
            //当用户登录失败时
            req.setAttribute("msg",e.getMessage());
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            //统一的错误页面
            resp.sendRedirect("error.jsp");
        }

    }
}
